<template>
  <!-- login view html start -->
  <view class="pageBox">
    <!-- 账号密码登录 -->
    <view v-if="!useWeChat">
      <image
        style="width: 100%; height: 100vh"
        src="https://newnw-oss.oss-cn-shanghai.aliyuncs.com/images/189427a9e2a80946c731704ca3a742e.png"
        mode=""
      ></image>
	  <view style="position: absolute;top: 186rpx;left: 50rpx;font-weight: 500;color: #fff;letter-spacing: 4rpx; ">
	    <view class="title">您好<image style="width: 280rpx; height: 80rpx;vertical-align: middle;margin-left: 10rpx;" src="@/static/login/hysy.png" mode=""></image></view>
	    <view style="font-size: 36rpx;">农污监测与运维管理系统</view>
	  </view>
      <view class="bottomBox">
          <view style="padding: 96rpx 50rpx 0 50rpx">
            <!-- <view style="display: flex; justify-content: space-between; margin-bottom: 20rpx" class="tabs">
              <view
                v-for="(item, index) in tabs"
                :key="index"
                class="tab"
                :class="{ tab_active: index === tabActive }"
                @click="tabChange(index)"
              >
                {{ item.label }}
              </view>
            </view> -->
            <u--form labelPosition="left" :model="ruleForm" ref="ruleForm" :borderBottom="false">
              <!-- 账号密码登录 -->
              <template v-if="tabActive === 0">
                <u-form-item prop="username">
                  <image src="@/static/login/account.png" style="display: inline-block;width: 29rpx; height: 32rpx;position: absolute;left: 42rpx;top: 28rpx;"></image>
                  <u--input v-model="ruleForm.username" placeholder="账号" border="none" > </u--input>
                  <!-- <u-icon
                      slot="right"
                      name="close-circle"
                  ></u-icon> -->
                  <image v-show="ruleForm.username" @click="ruleForm.username=''" slot="right" src="@/static/login/clear.png" style="width:34rpx; height: 34rpx;margin-right: 30rpx;"></image>
                </u-form-item>
                <u-form-item prop="password" >
                  <image src="@/static/login/password.png" style="display: inline-block;width: 28rpx; height: 34rpx;position: absolute;left: 42rpx;top: 28rpx;"></image>
                  <u--input v-model="ruleForm.password" :password='passwordType' placeholder="密码" border="none" > </u--input>
                  <!-- <image v-show="ruleForm.password" @click="ruleForm.password=''" slot="right" src="@/static/login/clear.png" style="width:34rpx; height: 34rpx;margin-right: 30rpx;"></image> -->
				  <image v-show="showPass" @click="seeTap" slot="right" src="@/static/icon/zy.png" style="width:43rpx; height: 33rpx;margin-right: 30rpx;"></image>
				  <image v-show="!showPass" @click="seeTap" slot="right" src="@/static/icon/biyan.png" style="width:43rpx; height: 33rpx;margin-right: 30rpx;"></image>
                </u-form-item>
                <!-- <u-form-item prop="code" >
                  <view style="position: relative; display: flex">
                    <view style="width: 100%">

                      <u--input v-model="ruleForm.code" placeholder="请输入验证码" border="none"> </u--input>
                    </view>
                    <view style="flex: none">
                      <template v-if="!codeImgForUsernamePassword">
                        <u-button
                          type="primary"
                          :text="getCodingForUsernamePassword ? codingNumForUsernamePassword + 's' : '获取验证码'"
                          :disabled="
                            getCodingForUsernamePassword ||
                            ruleForm.username === null ||
                            ruleForm.username === '' ||
                            ruleForm.password === null ||
                            ruleForm.password === ''
                          "
                          customStyle="width: 172rpx; height: 56rpx; background: #3576F2;border-radius: 4rpx;padding: 8rpx 16rpx;font-weight: 400;font-size: 28rpx;color: #ffffffe6"
                          @click="getCodeForUsernamePassword"
                        >
                        </u-button>
                      </template>
                      <template v-else>
                        <image
                          :src="codeImgForUsernamePassword"
                          style="width: 172rpx; height: 56rpx"
                          @click="getCodeForUsernamePassword"
                        ></image>
                      </template>
                    </view>
                  </view>
                </u-form-item> -->
              </template>
              <!-- 手机验证码登录 -->
              <template v-else-if="tabActive === 1">
                <u-form-item prop="phone" borderBottom>
                  <u--input v-model="ruleForm.phone" placeholder="请输入手机号" border="none" > </u--input>
                </u-form-item>
                <u-form-item prop="code" borderBottom>
                  <view style="position: relative; display: flex">
                    <view style="width: 100%">
                      <u--input v-model="ruleForm.code" placeholder="请输入验证码" border="none" > </u--input>
                    </view>
                    <view style="flex: none">
                      <template v-if="!codeImgForPhone">
                        <u-button
                          type="primary"
                          :text="getCodingForPhone ? codingNumForPhone + 's' : '获取验证码'"
                          :disabled="getCodingForPhone || ruleForm.phone === null || ruleForm.phone === ''"
                          customStyle="width: 172rpx; height: 56rpx; background: #3576F2;border-radius: 4rpx;padding: 8rpx 16rpx;font-weight: 400;font-size: 28rpx;color: #ffffffe6"
                          @click="getCodeForPhone"
                        >
                        </u-button>
                      </template>
                      <template v-else>
                        <div class="like-code-img" @click="getCodeForPhone">
                          {{ codeImgForPhone }}
                        </div>
                        <!--                        <image :src="codeImgForPhone" style="width: 172rpx; height: 56rpx;" @click="getCodeForPhone"></image>-->
                      </template>
                    </view>
                  </view>
                </u-form-item>
			
              </template>
            </u--form>
			<view class="remember-psw">
							<checkbox-group>
								<checkbox class="size" type="checkbox"  :checked='rememberPsw' @click="rememberPsw = !rememberPsw" color="#3c8aff"/>
								记住密码
							</checkbox-group>
						</view>
			<!-- <view class="">
				
				<image @click="isRemember=!isRemember" :src="isRemember?iconChecked:iconUnchecked" style="width: 20rpx; height: 20rpx;"></image>
				记住密码
			</view> -->
            <u-button
              type="primary"
              text="登录"
              :disabled="
                (tabActive === 0 &&
                  (ruleForm.username === null ||
                    ruleForm.username === '' ||
                    ruleForm.password === null ||
                    ruleForm.password === '')) ||
                (tabActive === 1 &&
                  (ruleForm.phone === null || ruleForm.phone === '' || ruleForm.code === null || ruleForm.code === ''))
              "
              customStyle="background: #3C8AFF; margin-top: 200rpx;border-radius: 20rpx;"
              @click="() => (tabActive === 1 ? loginByPhone() : login())"
            ></u-button>
            <!-- 第三方登录 -->
            <u-button
              v-if="false"
              type="primary"
              text="微信用户登录"
              customStyle="color: #3576F2; background: white; border: 2rpx solid #3576F2;border-radius: 8rpx;"
              @click="getKeyFn"
            ></u-button>
          </view>
      </view>
    </view>
    <view v-else>
      <view class="header">
        <!-- <image src="/static/img/public/login-wx.png"></image> -->
      </view>
      <!-- 微信登录     -->
      <view class="content">
        <view>申请获取以下权限</view>
        <text>获得你的公开信息(昵称，头像、地区等)</text>
      </view>
      <button
        class="bottom"
        type="primary"
        withCredentials="true"
        open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumber"
      >
        授权登录
      </button>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
  <!-- login view html end -->
</template>
<script>
import { getCode, login, getPhoneCode, phoneLogin, getKey } from '@/api/login';
import { get_token, set_token } from '@/auth/token';
import WXBizDataCrypt from '@/utils/WXBizDataCrypt.js';
import { getUserPermissionByToken } from '@/api/system';
import { customBaseFlatten } from '@/utils/fun';
import iconChecked from '@/static/icon/checked.png'
import iconUnchecked from '@/static/icon/unchecked.png'
export default {
  data() {
    return {
		passwordType:true,
		showPass:false, // 是否显示密码
		iconChecked,
		iconUnchecked,
      useWeChat: false,
      ruleForm: {
        username: '',
        password: '',
        phone: null,
        code: null,
      },
	  rememberPsw:true, //是否记住密码
      checkKey: null,
      getCodingForUsernamePassword: false,
      codingNumForUsernamePassword: 60,
      getCodingForPhone: false,
      codingNumForPhone: 60,
      codeImgForUsernamePassword: null,
      codeImgForPhone: null,
      code: null,
      appid: 'wx7a026389de794364',
      openid: null,
      session_key: null,
      unionid: null,
      tabActive: 0,
      tabs: [
        {
          label: '账号密码登录',
          value: '账号密码登录',
        },
        {
          label: '手机号登录',
          value: '手机号登录',
        },
      ],
    };
  },
  		mounted() {
  			// 取出缓存中的账号、密码
  			// const HBusername = uni.getStorageSync('HBusername');
  			// const HBpassword = uni.getStorageSync('HBpassword');
  			// console.log("缓存的账号:",HBusername)
  			// console.log("缓存的密码:",HBpassword)
  			// //有账号、密码就赋值给文本，没有就清空
  			// if (HBusername && HBpassword) {
  			// 	this.ruleForm.username = HBusername;
  			// 	this.ruleForm.password = HBpassword;
  			// }
  		},
  created() {
    // this.isRouterToHomePage();
    // 测试
    // uni.navigateTo({
    //   url: '/pages/home/home',
    // })
    // this.getCodeImgForUsernamePassword();
  },
  onShow() {
    // uni.clearStorageSync('identify')
	//取出缓存中的账号、密码
	const HBusername = uni.getStorageSync('HBusername');
	const HBpassword = uni.getStorageSync('HBpassword');
	console.log("缓存的账号:",HBusername)
	console.log("缓存的密码:",HBpassword)
	//有账号、密码就赋值给文本，没有就清空
	if (HBusername && HBpassword) {
		this.ruleForm.username = HBusername;
		this.ruleForm.password = HBpassword;
	}
  },
  methods: {
	  seeTap(){
		this.passwordType=!this.passwordType
		  this.showPass=!this.showPass
		  console.log('搭建及了');
	  },
    // isRouterToHomePage() {
    //   const token = get_token();
    //   if (token) {
    //     uni.switchTab({
    //       url: '/pages/home/home',
    //     });
    //   }
    // },
    getKeyFn() {
      getKey().then((res) => {
        let key = '';
        Object.keys(res.data).forEach((item) => {
          if (item.includes('t')) {
            key = res.data[item];
          }
        });
        this.getUserProfile(key);
      });
    },
    tabChange(index) {
      this.ruleForm.code = null;
      this.checkKey = null;
      this.tabActive = index;
    },
    getCodeForUsernamePassword() {
      // 获取验证码
      if (this.getCodingForUsernamePassword) {
        return;
      }
      this.getCodingForUsernamePassword = true;
      const interval = setInterval(() => {
        this.codingNumForUsernamePassword--;
        if (this.codingNumForUsernamePassword <= 0) {
          clearInterval(interval);
          this.codingNumForUsernamePassword = 60;
          this.getCodingForUsernamePassword = false;
        }
      }, 1000);
      this.getCodeImgForUsernamePassword();
    },
    getCodeForPhone() {
      // 获取验证码
      if (this.getCodingForPhone) {
        return;
      }
      this.getCodingForPhone = true;
      const interval = setInterval(() => {
        this.codingNumForPhone--;
        if (this.codingNumForPhone <= 0) {
          clearInterval(interval);
          this.codingNumForPhone = 60;
          this.getCodingForPhone = false;
        }
      }, 1000);
      this.getCodeImgForPhone();
    },
    getCodeImgForUsernamePassword() {
      this.codeImgForUsernamePassword = null;
      this.checkKey = Math.ceil(Math.random() * 1000000000000); // 1684223429356
      getCode(this.checkKey)
        .then((res) => {
          const base64CodeImg = res.data.result;
          this.codeImgForUsernamePassword = base64CodeImg;
          this.getCodingForUsernamePassword = false;
        })
        .catch((err) => {});
    },
    getCodeImgForPhone() {
      this.codeImgForPhone = null;
      const params = {
        mobile: this.ruleForm.phone,
        smsmode: 0,
      };
      getPhoneCode(params)
        .then((res) => {
          const base64CodeImg = res.data.result;
          this.codeImgForPhone = base64CodeImg;
          this.getCodingForPhone = false;
        })
        .catch((err) => {});
    },
    login() {
      // 先使用账号密码登录
      const params = {
        captcha: this.ruleForm.code,
        checkKey: this.checkKey,
        password: this.ruleForm.password,
        username: this.ruleForm.username,
      };
      login(params)
        .then((res) => {
          // this.$refs.uToast.show({
          //   message: res.data.message,
          //   type: res.data.code === 200 ? 'success' : 'warning',
          // });
          console.log(res,res.data.code, res.data.code === 200,'resss')
          if (res.data.code === 200) {
            const token = res.data.result.token;
            const userInfo = res.data.result.userInfo;
			if (this.rememberPsw) {
											uni.setStorageSync('HBusername', this.ruleForm.username);
											uni.setStorageSync('HBpassword', this.ruleForm.password);
											// console.log(uni.getStorageSync('HBusername'),uni.getStorageSync('HBpassword'),'88888888888888');
										} else {//销毁缓存中的账号、密码
											uni.removeStorageSync('HBusername');
											uni.removeStorageSync('HBpassword');
										}
            console.log(userInfo.orgType === '6' ? '/pages/area/index' : '/pages/areaList/index')
            this.setInfo(token, userInfo);
            uni.reLaunch({
              url: '/pages/home/home',
            });
          }
        })
        .catch((e) => {});
    },
    // 手机号登录-验证码固定
    loginByPhone() {
      // 先使用手机号登录
      const params = {
        mobile: this.ruleForm.phone,
        captcha: this.ruleForm.code,
      };
      phoneLogin(params).then((res) => {
        const token = res.data.result.token;
        const userInfo = res.data.result.userInfo;
        this.setInfo(token, userInfo);
        uni.switchTab({
          url: '/pages/home/home',
        });
      });
    },
    // 保存token 和 phone
    setInfo(token, info) {
      // 存下token
      set_token(token);
      // console.log('userInfo', info)
      // 存departIds
      uni.setStorageSync('departIds', info.departIds);
      uni.setStorageSync('regionId', info.departIds.split(',')[0]); // 默认取第一个
      // 存权限字段orgType 6为三级权限，其余都为二级
      uni.setStorageSync('orgType', info.orgType)
      // 存角色标识
      uni.setStorageSync('role', info.role)
      // 存用户id
      uni.setStorageSync('userId', info.id)

      // 存下手机号
      uni.setStorageSync('phone', info.phone);
      uni.setStorageSync('username', info.username);
	  uni.setStorageSync('realname', info.realname);
	  uni.setStorageSync('avatar', info.avatar);
      // 存下权限菜单列表
      getUserPermissionByToken().then((res) => {
        // 存下对应权限的菜单列表
        const menu = res.data.result.menu;
        const menuList = customBaseFlatten(menu);
        uni.setStorageSync('menu', menu);
        uni.setStorageSync('menuList', menuList);
      });
    },
    // 第三方登录
    getUserProfile(key) {
      this.useWeChat = true;
      uni.getUserProfile({
        desc: '登录',
        success: (info) => {
          //这里取到的是用户的信息，自己安排自己的业务
          uni.login({
            provider: 'weixin',
            success: (res) => {
              this.code = res.code;
              //这里获取的是用户的code，用来换取 openid、unionid、session_key 等信息，再将信息丢给后台自己的登录业务就行了
              // return
              uni.request({
                url: 'https://api.weixin.qq.com/sns/jscode2session',
                method: 'GET',
                data: {
                  appid: this.appid, //你的小程序的APPID
                  secret: key,
                  js_code: this.code, //wx.login 登录成功后的code
                  grant_type: 'authorization_code',
                },
                success: (cts) => {
                  // 换取成功后 暂存这些数据 留作后续操作
                  this.openId = cts.data.openid; //openid 用户唯一标识
                  this.unionid = cts.data.unionid; //unionid 开放平台唯一标识   当公众号和小程序同时登录过才会有
                  this.session_key = cts.data.session_key; //session_key  会话密钥
                },
              });
            },
          });
        },
        fail: (err) => {
          // console.log(err);
        },
      });
    },
    // 解密
    getPhoneNumber(e) {
      // console.log(e.detail.errMsg) // 判断用户是否允许获取手机号
      // console.log(e);
      let pc = new WXBizDataCrypt(this.appid, this.session_key);
      let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
      /*data = {countryCode: "86"
				phoneNumber: "17857026926"
				purePhoneNumber: "17857026926"} */
      console.log(data); //data就是最终解密的用户信息
    },
  },
  onLoad(options) {
    //默认加载
    // this.getUserProfile();
  },
};
</script>
<style lang="scss" scoped>
	.bottomBox{
		position: absolute;
		bottom: 0; 
		width: 100%; 
		height: 74%; 
		display: flex; 
		flex-direction: column;
		background: linear-gradient( 180deg, rgba(255,255,255,0.89) 0%, rgba(255,255,255,0.6) 100%);
		border-radius: 30rpx 30rpx 0rpx 0rpx;
	}
	.title{
		font-size: 60rpx;
		margin-bottom: 28rpx;
	}
/deep/.u-form-item{
  border-radius: 20rpx;
  padding-left: 100rpx;
  margin-bottom: 48rpx;
  position: relative;
  background: #FFFFFF;
  box-shadow: 0rpx 6rpx 12rpx 2rpx rgba(92,203,174,0.1);
}

.tabs {
  .tab {
    padding: 0 20rpx 20rpx 20rpx;
  }

  .tab_active {
    color: #1890ff;
    text-shadow: 0 0 0.25px currentColor;
    transition: color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
    border-bottom: 2px #1890ff solid;
  }
}

.like-code-img {
  background: rgba(53, 118, 242, 0.5);
  padding: 8rpx 16rpx;
  color: #ffffffe6;
  font-size: 28rpx;
}
.header {
  margin: 90rpx 0 90rpx 50rpx;
  border-bottom: 1px solid #ccc;
  text-align: center;
  width: 650rpx;
  height: 300rpx;
  line-height: 450rpx;
}

.header image {
  width: 200rpx;
  height: 200rpx;
}

.content {
  margin-left: 50rpx;
  margin-bottom: 90rpx;
}

.content text {
  display: block;
  color: #9d9d9d;
  margin-top: 40rpx;
}

.bottom {
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
}
.remember-psw{
	margin-left: 220rpx;
	font-weight: 400;
	font-size: 28rpx;
	color: #000000;
	.size {
		 transform: scale(0.8,0.8);
	}
}
</style>
